package com.c2b.algorithm.leetcode.base;

/**
 * <a href='https://leetcode.cn/problems/number-of-islands/description/'>岛屿数量(Number of Islands)</a>
 * <p>给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。</p>
 * <p>岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。</p>
 * <p>此外，你可以假设该网格的四条边均被水包围。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：grid = [
 *        ['1','1','1','1','0'],
 *        ['1','1','0','1','0'],
 *        ['1','1','0','0','0'],
 *        ['0','0','0','0','0']
 *      ]
 *      输出：1
 *
 * 示例 2：
 *      输入：grid = [
 *        ['1','1','0','0','0'],
 *        ['1','1','0','0','0'],
 *        ['0','0','1','0','0'],
 *        ['0','0','0','1','1']
 *      ]
 *      输出：3
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>m == grid.length</li>
 *         <li>n == grid[i].length</li>
 *         <li>1 <= m, n <= 300</li>
 *         <li>grid[i][j] 的值为 '0' 或 '1'</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/26 14:02
 */
public class LC0200NumberOfIslands_M {

    static class Solution {
        public int numIslands(char[][] grid) {
            if (grid == null || grid.length == 0) {
                return 0;
            }
            int ret = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == '1') {
                        dfs(i, j, grid);
                        ret++;
                    }
                }
            }
            return ret;
        }

        private void dfs(int row, int col, char[][] grid) {
            // 边界条件校验
            if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == '0') {
                return;
            }
            grid[row][col] = '0';
            // 上下左右
            dfs(row - 1, col, grid);
            dfs(row + 1, col, grid);
            dfs(row, col - 1, grid);
            dfs(row, col + 1, grid);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.numIslands(
                new char[][]{
                        {'1', '1', '1', '1', '0'},
                        {'1', '1', '0', '1', '0'},
                        {'1', '1', '0', '0', '0'},
                        {'0', '0', '0', '0', '0'},

                }
        ));

        System.out.println(solution.numIslands(
                new char[][]{
                        {'1', '1', '0', '0', '0'},
                        {'1', '1', '0', '0', '0'},
                        {'0', '0', '1', '1', '0'},
                        {'0', '0', '0', '0', '1'},

                }
        ));
    }
}
